package logic

import (
	"context"
	"errors"
	"time"

	"test-api/internal/model"
	"test-api/internal/svc"
	"test-api/internal/types"

	"github.com/golang-jwt/jwt/v4"
	"github.com/zeromicro/go-zero/core/logx"
	"gorm.io/gorm"
)

type UserLoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserLoginLogic) UserLogin(req *types.STUserLoginReq) (resp *types.STUserLoginRsp, err error) {
	resp = &types.STUserLoginRsp{}

	v, err := l.getUserByMobile(req.Mobile)

	if err != nil {
		return resp, err
	}

	resp.Token, err = l.getToken(v.Id)

	return resp, nil
}

func (l *UserLoginLogic) getToken(userId int64) (string, error) {
	iat := time.Now().Unix()

	claims := make(jwt.MapClaims)
	claims["exp"] = iat + l.svcCtx.Config.Auth.AccessExpire
	claims["iat"] = iat
	claims["userId"] = userId

	t := jwt.New(jwt.SigningMethodHS256)
	t.Claims = claims

	token, err := t.SignedString([]byte(l.svcCtx.Config.Auth.AccessSecret))

	return token, err
}

func (l *UserLoginLogic) getUserByMobile(mobile string) (*model.User, error) {
	v := &model.User{}
	db := l.svcCtx.DB.Model(&model.User{}).Where("mobile = ?", mobile).Where("state = 1")

	if err := db.First(&v).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return v, nil
		}
		return v, errors.New("数据库错误")
	}

	return v, nil
}
